﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using System.Configuration;

namespace WOLService
{
    public partial class WOLService : ServiceBase
    {
        public string mqtt_server = "119.91.90.201";
        public int mqtt_port = 1883;
        public string username = "guest";
        public string password = "guest";
        public string clientId = "wol_controller";
        public string topic = "hw/home/wol";
        MqttClient client;

        MqttClient ConnectMQTT(string broker, int port, string clientId, string username, string password)
        {
            client = new MqttClient(broker, port, false, MqttSslProtocols.None, null, null);
            client.Connect(clientId, username, password);
            if (client.IsConnected)
            {
                Console.WriteLine("Connected to MQTT Broker");
            }
            else
            {
                Console.WriteLine("Failed to connect");
            }
            return client;
        }

        /// <summary>
        /// 远程开机，网卡需要具备远程唤醒功能
        /// </summary>
        /// <param name="mac">网卡物理地址字符数组</param>
        public void WakeUp(byte[] mac)
        {
            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 9090);

            byte[] packet = new byte[17 * 6];

            for (int i = 0; i < 6; i++)
                packet[i] = 0xFF;

            for (int i = 1; i <= 16; i++)
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = mac[j];

            int result = client.Send(packet, packet.Length);
        }

        public WOLService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            mqtt_server = ConfigurationManager.AppSettings["MqttAddress"];
            mqtt_port = Convert.ToInt32(ConfigurationManager.AppSettings["MqttAddress"]);
            clientId = ConfigurationManager.AppSettings["clientId"];
            username = ConfigurationManager.AppSettings["username"];
            password = ConfigurationManager.AppSettings["password"];
            topic = ConfigurationManager.AppSettings["Topic"];

            MqttClient client = ConnectMQTT(mqtt_server, mqtt_port, clientId, username, password);
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            client.Subscribe(new string[] { topic }, new byte[] { 0 });
        }

        private void Client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            //throw new NotImplementedException();
            WakeUp(e.Message);
        }

        protected override void OnStop()
        {
            client.Disconnect();
        }
    }
}
